package project6.voip;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.util.Log;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

public class VoiceCaptureClient extends Thread 
{
	
	private static final String TAG = "VCC";
	static public DatagramSocket socket;
	private String server;
	private int serverPort; 
	
	AudioRecord recorder;
	private int sampleRate = 8000;
	private int cConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
	private int aFormat = AudioFormat.ENCODING_PCM_16BIT;
	
	private boolean end;

VoiceCaptureClient(String server, int port) 
{
	super();
	this.end=false;
	this.server = server;
	this.serverPort = port;
}

public void run() 
{
	try 
	{
		android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
		DatagramPacket packet;
		byte[][] buffers = new byte[256][160];
		int k = 0;
		int minBuf = AudioRecord.getMinBufferSize(sampleRate,cConfig,aFormat);
		InetAddress serverAddr = null;
		try
		{
			serverAddr = InetAddress.getByName(server);		
		}
		catch(UnknownHostException a){
			System.out.println("ERROR!!!!");
		}
		try
		{
			socket = new DatagramSocket();
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage() + " 1");
		}		
		try
		{
			System.out.println("creating recorder");
			recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,sampleRate,cConfig,aFormat,minBuf*10);
			recorder.startRecording();
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage()+ " 2");
		}		
		
		byte[] buffer=null;
		while(!end) 
		{
			try 
			{			
				buffer = buffers[k++ % buffers.length];
				minBuf = recorder.read(buffer,0,buffer.length);			
				packet=new DatagramPacket(buffer,buffer.length,serverAddr,serverPort);
				/*String test = "user";
				System.out.println("server" + server);
				System.out.println("serverAddr" + serverAddr);
				packet=new DatagramPacket(test.getBytes(), 2, serverAddr, serverPort);*/
				socket.send(packet);			
			} 
			catch (Exception e) 
			{
				Log.e(TAG, "C: Error", e);
			}
		}
	}
	catch(Exception e) 
	{
		Log.e(TAG,e.toString());
		this.interrupt();
	}
}
public void close() 
{
	end=true;
	if(recorder != null) 
	{
		recorder.release();
	}
}
}
